import openpyxl

def xlsx_to_latex_table(xlsx_path, sheet_name=None, output_path=None):
   
    wb = openpyxl.load_workbook(xlsx_path, data_only=True)
    sheet = wb[sheet_name] if sheet_name else wb.active

    rows = list(sheet.iter_rows(values_only=True))
    if not rows:
        print("空表格")
        return

    num_cols = len(rows[0])
    col_format = "c" * num_cols  # 所有列居中对齐（无 |）

    # 构建 LaTeX 表格
    latex_lines = [
        "\\begin{table}[htbp]",
		"\\centering",
		"\\caption{表名}",
		"\\label{标签}",
        "\\begin{tabular}{" + col_format + "}",
        "\\hline"
    ]

    for i, row in enumerate(rows):
        line = " & ".join([str(cell) if cell is not None else "" for cell in row]) + " \\\\"
        latex_lines.append(line)
        if i == 0:  
            latex_lines.append("\\hline")

    latex_lines.append("\\hline")
    latex_lines.append("\\end{tabular}")
    latex_lines.append("\\end{table}")

    latex_table = "\n".join(latex_lines)

    # 输出
    if output_path:
        with open(output_path, "w", encoding="utf-8") as f:
            f.write(latex_table)
        print(f"LaTeX 表格已保存到: {output_path}")
    else:
        print(latex_table)


xlsx_to_latex_table("training1/handled/四类文物统计.xlsx", output_path="table.tex")
